<?php
class EbayFetcher extends AbstractFetcher {
	const ENDPOINT = 'http://open.api.ebay.com/shopping?callname=GetSingleItem&responseencoding=XML&appid=%APPID%&version=515&ItemID=%ITEMID%&IncludeSelector=TextDescription';
	private $ebayItem = null;
	
	/**
	 * @see AbstractFetcher#setContentInformation()
	 */
	protected function setContentInformation(){
		//only able to handle items, no cats or user pages etc. for those GenericFetcher will be used
		//http://cgi.ebay.de/ws/eBayISAPI.dll?ViewItem&item=140373875226&ssPageName=STRK:MESELX:IT#ht_500wt_1182
		if(preg_match('/http:\/\/.*eBayISAPI.dll\?ViewItem.*item=(\d+)/', $this->url, $matches) !== false && count($matches) == 2){
			$this->contentInformation = $matches[1];
			return $this->loadEbayItem();
		}
		else{
			return false;
		}
	}
	
	/**
	 * @see AbstractFetcher#setTitle()
	 */
	protected function setTitle(){
		$this->title = (string)$this->ebayItem->Title;
	}
	
	/**
	 * @see AbstractFetcher#setDescription()
	 */
	protected function setDescription(){
		//$this->description =(string)$this->ebayItem->PrimaryCategoryName;
		$this->description = (string)$this->ebayItem->Description;
		if(strlen($this->description) > 200){
			$this->description = substr($this->description, 0, 197).'...';
		}
		
	}
	
	/**
	 * @see AbstractFetcher#setPreviewImages()
	 */
	protected function setPreviewImages(){
		if($this->ebayItem->PictureURL){
			$this->previewImages[] = (string)$this->ebayItem->PictureURL;
		}
	}
	
	private function loadEbayItem(){
		if(!defined('EBAY_API_KEY')){
			return false;
		}
		$search = array('%APPID%', '%ITEMID%');
		$replace = array(EBAY_API_KEY, $this->contentInformation);
		$url = str_replace($search, $replace, self::ENDPOINT);
		$xml = simplexml_load_file($url);
		if(!$xml){
			return false;
		}
		$this->ebayItem = $xml->Item;
		return true;
	}
}